package org.springrain.testjpa.config;

import org.apache.commons.lang3.StringUtils;

/**
 * @author springrain
 * @version 1.0
 **/
public class DynamicRoutingDataSourceContext {

    public static final String MASTER = "master";
    public static final String SLAVE = "slave";

    private static final ThreadLocal<String> threadLocalDataSource = new ThreadLocal<>();

    public static String getRoutingDataSource() {
        String dataSourceType = threadLocalDataSource.get();
        // if (dataSourceType == null) {
        //threadLocalDataSource.set(DynamicRoutingDataSourceContext.SLAVE);
        // return getRoutingDataSource();
        // return null;
        //  }
        // System.err.println(Thread.currentThread().getName()+" get RoutingDataSource : " + dataSourceType);
        if (StringUtils.isBlank(dataSourceType)) {
            dataSourceType = DynamicRoutingDataSourceContext.SLAVE;
        }
        return dataSourceType;
    }

    public static void setRoutingDataSource(String dataSource) {
        if (dataSource == null) {
            throw new NullPointerException();
        }
        threadLocalDataSource.set(dataSource);
        // System.err.println(Thread.currentThread().getName()+" set RoutingDataSource : " + dataSource);
    }

    public static void removeRoutingDataSource() {
        threadLocalDataSource.remove();
        // System.err.println(Thread.currentThread().getName()+" remove RoutingDataSource");
    }
}
